#include <sys/socket.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/un.h>


int main(){
    int sockfd=socket(AF_LOCAL,SOCK_STREAM,0);
    if(sockfd<0){
        perror("socket error");
        exit(1);
    }
    //本地通信与网络通信的不同
    struct sockaddr_un addr;
    addr.sun_family=AF_LOCAL;
    strcpy(addr.sun_path,"/tmp/ymbxsock");

    int ret=bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
    if(ret<0){
        perror("bind error");
        exit(2);
    }
    int lfd=listen(sockfd,10);
    if(lfd<0){
        perror("listen error");
        exit(3);
    }
    int cfd=accept(sockfd,NULL,NULL);
    if(cfd<0){
        perror("accept error");
        exit(4);
    }
    char buffer[1024];
    while(1){
        memset(buffer,0,sizeof(buffer));
        ssize_t n=read(cfd,buffer,sizeof(buffer)-1);
        if(strncmp(buffer,"quit",4)==0){
            close(cfd);
            break;
        }
        if(n>0){
            buffer[n]='\0';
            printf("client say:%s",buffer);
            fflush(stdout);
        }else if(n==0){
            printf("client closed\n");
            close(cfd);
        }else{
            perror("read error");
            close(cfd);
        }
        sleep(1);
        
        
    }
    close(sockfd);
    unlink("/tmp/ymbxsock");
    return 0;
}